<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
        <el-form-item prop="productionTimeStart" :label="$t('qms.productionTime')">
          <el-date-picker style="width: 380px"
                          v-model="state.queryForm.productionTime"
                          type="datetimerange"
                          @change="changeProductionTime"
                          range-separator="To"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          :start-placeholder="$t('iot.startTime')"
                          :end-placeholder="$t('iot.endTime')"
          />
        </el-form-item>
        <el-form-item prop="barcode" :label="$t('qms.barCode')">
          <el-input style="width: 140px" v-model="state.queryForm.barcode" clearable :placeholder="$t('qms.barCode')"/>
        </el-form-item>
        <el-form-item prop="materialCode" :label="$t('iot.materialCode')">
          <el-input style="width: 140px" v-model="state.queryForm.materialCode" clearable :placeholder="$t('iot.materialCode')"/>
        </el-form-item>
        <el-form-item prop="processName" :label="$t('iot.processName')">
          <el-input style="width: 140px" v-model="state.queryForm.processName" clearable :placeholder="$t('iot.processName')"/>
        </el-form-item>
        <el-form-item prop="materialCode" :label="$t('qms.checkTypeCode')">
          <el-select :placeholder="$t('qms.checkTypeCode')"
                     style="width: 140px"
                     filterable
                     remote
                     @change="changeQcStatus"
                     :remote-method="getQcStatus"
                     v-model="state.queryForm.qcStatus">
            <el-option v-for="item in qcStatusList"
                       :key="item.text"
                       :label="item.text"
                       :value="item">
              <span style="float: left">{{ item.text }}</span>
              <span style=" float: right;  color: var(--el-text-color-secondary);  font-size: 13px; "> {{
                  item.value
                }} </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button icon="search" type="primary"  @click="getDataList">{{$t('btn.search')}}</el-button>
          <el-button icon="refresh" plain @click="resetQuery">{{$t('btn.reset')}}</el-button>
          <el-button icon="Check" v-auth="'platform_qmsProductionCheck_add'" type="warning"
                     @click="updateBarcodePass('pass',selectObjs) ">{{$t('qms.batchApproval')}}
          </el-button>
          <el-button icon="Close" v-auth="'platform_qmsProductionCheck_del'" type="info"
                     @click="updateBarcodePass('fail',selectObjs)">{{$t('qms.batchRejection')}}
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="state.dataList" v-loading="state.loading" border
                :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                @selection-change="selectionChangHandle" style="width: 100%;height: 100%;"
                @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center"/>
        <el-table-column prop="barcode" :label="$t('qms.barCode')" show-overflow-tooltip/>
        <el-table-column prop="materialCode" :label="$t('iot.materialCode')" show-overflow-tooltip/>
        <el-table-column prop="materialName" :label="$t('iot.materialName')" show-overflow-tooltip/>
        <el-table-column prop="processCode" :label="$t('iot.processCode')" show-overflow-tooltip/>
        <el-table-column prop="processName" :label="$t('iot.processName')" show-overflow-tooltip/>
        <el-table-column prop="currentQty" :label="$t('qms.currentQty')" show-overflow-tooltip/>
        <el-table-column prop="productionTime" :label="$t('qms.productionTime')" show-overflow-tooltip/>
        <el-table-column :label="$t('qms.checkState')" show-overflow-tooltip>
          <el-table-column prop="qcStatus" :label="$t('qms.primaryDetectionState')" show-overflow-tooltip/>
          <el-table-column prop="secondQcStatus" :label="$t('qms.secondaryDetectionState')" show-overflow-tooltip>
            <template #default="scope">
              <el-tag
                  :type="scope.row.secondQcStatus === 'pass' ? 'pass' : (scope.row.secondQcStatus === 'fail' ?'danger':'warning')">
                {{
                  scope.row.secondQcStatus === 'pass' ? $t('qms.Pass') : (scope.row.secondQcStatus === 'fail' ? $t('qms.fail') : $t('qms.waitForInspection'))
                }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table-column>

      </el-table>
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination"/>
    </div>


  </div>
</template>

<script setup lang="ts" name="systemQmsProductionCheck">
import {BasicTableProps, useTable} from "/@/hooks/table";
import {delObjs, qmsCheckFailBarcode, updateSecondQcStatus} from "/@/api/platform/qms/qmsProductionCheck";
import {useMessage, useMessageBox} from "/@/hooks/message";
import {fetchCheckList} from "/@/api/platform/qms/qmsRelationH";
import {useI18n} from "vue-i18n";

const {t} = useI18n();

// 搜索变量
const queryRef = ref()
const qcStatusList = ref([
  {
    text: '全部',
    value: ''
  }
])

// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: qmsCheckFailBarcode
})

const changeProductionTime = (data) => {
  state.queryForm.productionTimeStart = data[0]
  state.queryForm.productionTimeEnd = data[1]
}

const changeQcStatus = (data) => {
  state.queryForm.qcStatus = data.value
}

async function fetchData() {
  try {
    const res = await fetchCheckList({
      "code": "InspectionStatus"
    });

    if (res.code === 0) {
      res.data.forEach(item => {
        qcStatusList.value.push({
          text: item.text,
          value: item.value
        });
      });
    }
  } catch (error) {
    useMessageBox().error(t('qms.FailedSelectTestType'))
  }
}

onMounted(async () => {
  await fetchData();
});


//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)

// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  state.queryForm = {}
  // 清空多选
  selectObjs.value = []
  getDataList(false)
}

// 导出excel
const exportExcel = () => {
  downBlobFile('/platform/qmsProductionCheck/export', Object.assign(state.queryForm, {ids: selectObjs}), 'qmsProductionCheck.xlsx')
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({id}) => id);
  multiple.value = !objs.length;
};

const updateBarcodePass = (type, ids) => {
  if (ids.length === 0) {
    useMessage().error('请选择一条数据')
    return
  }
  let datas = [];
  ids.forEach(x => {
    let id = {id: x}
    datas.push(id)
  })
  console.log('bianj')
  updateSecondQcStatus(
      {secondQcStatus: type, barcodeList: datas}
  ).then(res => {
    if (res.code === 0) {
      useMessage().success('操作成功')
      getDataList()
    } else {
      useMessage().error(res.msg)
    }
  }).catch(reason => {
    useMessage().error(reason.msg)
  })
}

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
</script>